package xyz.msj.hrm.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.msj.hrm.domain.Tenant;
import xyz.msj.hrm.domain.Employee;
import xyz.msj.hrm.domain.dto.TenantDTO;
import xyz.msj.hrm.mapper.TenantMapper;
import xyz.msj.hrm.service.ITenantService;
import xyz.msj.hrm.mapper.EmployeeMapper;
import xyz.msj.hrm.util.StrUtils;
import xyz.msj.hrm.util.encrypt.MD5;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mushengjie
 * @since 2020-09-10
 */
@Service
@Transactional //开启事务
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    //用户mapper
    @Autowired
    private EmployeeMapper employeeMapper;


    //获取过期时间
    @Value("${hrm.system.expiredate}")
    private int expireDate;
    /**
     * 保存公司注册
     *
     * @param tenantDTO
     */
    @Override
    public void insertTenantDTO(TenantDTO tenantDTO) {
        //接收参数
        //员工
        Employee employee = tenantDTO.getEmployee();
        //公司
        Tenant tenant = tenantDTO.getTenant();
        //公司类型id
        int mealId = tenantDTO.getMealId();
        //对接收到的参数进行判断 稍后写
        if (StringUtils.isEmpty(tenant.getCompanyName())) {
            throw new RuntimeException("公司名不能为空！");
        }
        //判断用户名
        if (StringUtils.isEmpty(employee.getUsername())) {
            throw new RuntimeException("用户名不能为空！");
        }

        //创建一个时间对象
        Date now = new Date();

        //保存公司信息
        //设置电话为null
        tenant.setCompanyNum(null);
        //设置时间为当前时间
        tenant.setRegisterTime(now);
        //设置状态
        tenant.setState(false);
        //进行保存，设置没有数据的值，是为了保证安全性，避免别人恶意注入包，返回公司id
        baseMapper.insert(tenant);

        //保存用户
        //设置真实姓名为null
        employee.setRealName(null);
        //获取盐值
        String salt = StrUtils.getComplexRandomString(10);
        //设置盐值
        employee.setSalt(salt);
        //设置密码
        employee.setPassword(MD5.getMD5(employee.getPassword()+salt));
        //设置注册时间
        employee.setInputTime(now);
        //设置状态(默认正常)
        employee.setState(Employee.NORMAL_CONDITION);
        //设置部门id
        employee.setDeptId(null);
        //设置员工类型 默认为管理员
        employee.setType(Employee.EMPLOYEE_ADMIN);
        //设置公司id
        employee.setTenantId(tenant.getId());
        //保存用户
        employeeMapper.insert(employee);

        //保存公司和套餐类型中间表
        baseMapper.insertMealWithTenant(mealId,tenant.getId(), DateUtils.addDays(now,expireDate),Tenant.UNPAID);

    }
}
